package cn.tedu.knows.gateway.service;

import cn.tedu.knows.commons.model.Permission;
import cn.tedu.knows.commons.model.Role;
import cn.tedu.knows.commons.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Component
@Slf4j
public class UserDetailsServiceImpl implements
                                        UserDetailsService {
    @Resource
    private RestTemplate restTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //Ribbon调用sys模块中根据用户名获得用户对象的Rest接口
        //?之后的username必须和控制器方法参数名称一致才能顺利赋值
        // =号之后的{}是占位符,后面会为它赋值,其中的数字从1开始
        String url="http://sys-service/v1/auth/user?username={1}";
        //getForObject第三个参数开始是可以为{}赋值的,
        //第三个参数赋值给{1},第三个参数赋值给{2},以此类推
        User user=restTemplate
                .getForObject(url,User.class,username);
        if(user==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        url="http://sys-service/v1/auth/permissions?userId={1}";
        //如果控制器方法返回值是List或其它集合类型
        //因为传递时自动转换为json格式,所以接收的时候需要改成数组
        Permission[] ps=restTemplate.getForObject(
                url,Permission[].class,user.getId());
        url="http://sys-service/v1/auth/roles?userId={1}";
        Role[] rs=restTemplate.getForObject(
                url,Role[].class,user.getId());
        if(ps==null || rs==null)
            throw new UsernameNotFoundException("没有权限登录");

        //构建auth数组,这个数组中包含当前登录用户的所有权限和角色
        String[] auth=new String[ps.length+rs.length];
        //开始遍历
        int i=0;
        for(Permission p: ps)
            auth[i++]=p.getName();
        for(Role r : rs)
            auth[i++]=r.getName();
        UserDetails u= org.springframework.security.core.userdetails.User
                .builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .accountLocked(user.getLocked()==1)
                .disabled(user.getEnabled()==0)
                .authorities(auth)
                .build();
        //千万别忘了返回
        return u;
    }
}
